module RoomHelper
  
  $classes = ["SI-003", "SI-004", "SI-006", "SI-007", "SI-008", "SI-013", "SI-015"]
  $at_rooms = [@class003, @class004, @class006, @class007, @class008, @class013, @class015]
  #This represents the time offset in the events.
  #For example 0 means that the the evenst will be display in the current time
  $time_offset = [0, 1, 6, 30] 
  
  def query_room_events
#   @event_hash = Announcement.find_by_sql("SELECT * FROM announcements WHERE start >= #{current_time} and start <= #{in_a_week_time}")
    for counter in 0..$classes.length-1
      $at_rooms[counter] = select_events_in(Integer(params[:show]), $classes[counter])
    end
    @class003 = $at_rooms[0]
    @class004 = $at_rooms[1]
    @class006 = $at_rooms[2]
    @class007 = $at_rooms[3]
    @class008 = $at_rooms[4]
    @class013 = $at_rooms[5]
    @class015 = $at_rooms[6]
    
    
    announcements = Announcement.find_by_sql("SELECT * FROM announcements WHERE place = 'SI-015' order by start asc")
    puts '_________________________________________'
    announcements.each do |e|
      puts e.title
    end
     
    case params[:show]
      when $time_offset[0].to_s then @calendar_type = "mains/in_time"
      when $time_offset[1].to_s then @calendar_type = "mains/all_day"  
      when $time_offset[2].to_s then @calendar_type = "mains/in_a_week"
      when $time_offset[3].to_s then @calendar_type = "mains/in_a_month"
    end
    
   # NOTICE!! param main is just a flag that comes form the show.html, shows if it is an ajax remote link or not.
    is_it_not_remote = unless params[:main] != nil then true else false end   # WTF
     
    if(is_it_not_remote)
      respond_to do |format|
        format.html # show.html.erb
        format.xml  { render :xml => @seminar }
      end
    else
      render :partial => 'room/templates/mains/all_day'
    end
  end


  # this is a workaround mehtod since the query in the show method does not work!!!. Is not comparing the time stamps!
  def select_events_in(offset, room)
    current_time = Time.now
    add_time = (60 * 60 * 24)*offset
    in_a_time = current_time + add_time
 
    announcements = Announcement.find_by_sql("SELECT * FROM announcements WHERE place = '#{room}' order by start asc")
    counter = 0
    result = []
    announcements.each do |a|
      
      if(offset == 0)
        if((a.start <= current_time) && (a.end >= current_time))
          result[counter] = a
          counter+=1
        end
      elsif(offset == 1) 
        if((a.end >= current_time) && (a.end.day == current_time.day))
          result[counter] = a
          counter+=1
        end
      elsif((a.end >= current_time) && (a.end <= in_a_time)) 
        result[counter] = a
        counter+=1
      end
    end
    return result
  end
  
end
